package cn.jesin.css.service.impl;

import cn.jesin.css.common.OthType;
import cn.jesin.css.entity.OtherAuth;
import cn.jesin.css.entity.User;
import cn.jesin.css.mapper.OtherAuthMapper;
import cn.jesin.css.mapper.UserMapper;
import cn.jesin.css.service.RegisterService;
import cn.jesin.css.utils.DataCheckUtil;
import cn.jesin.css.vo.OtherAuthInfo;
import jakarta.annotation.Resource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 谷汉斌
 * @description
 * @createTime 2024/8/13 下午1:44
 */
@Service
public class RegisterServiceImpl implements RegisterService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private OtherAuthMapper otherAuthMapper;

    /**
     * 手机号+密码注册
     *
     * @param otherAuthInfo 第三方信息
     * @return 注册成功返回true，否则返回false
     */
    @Override
    public boolean phonePasswordRegister(OtherAuthInfo otherAuthInfo) {
        //校验手机号码
        if (!DataCheckUtil.isValidPhoneNumber(otherAuthInfo.getPhone())) {
            return false;
        }
        // 判断手机号是否已被注册
        if (null != otherAuthMapper.selectOtherAuthByoAuthTypeAndoAuthId(OthType.PHONE.getType(), otherAuthInfo.getPhone())) {
            return false;
        }
        // 创建一个 SimpleDateFormat 对象，并指定日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String flag = sdf.format(new Date());
        String username = flag + otherAuthInfo.getPhone();
        // 插入第三方认证信息表
        OtherAuth otherAuth = OtherAuth.builder()
                .username(username)
                .oAuthType(OthType.PHONE.getType())
                .oAuthId(otherAuthInfo.getPhone())
                .build();
        //插入到第三方认证信息表并获取主键id
        int id = otherAuthMapper.insertOtherAuth(otherAuth);
        if (id == 0) {
            return false;
        }
        String password = new BCryptPasswordEncoder().encode(otherAuthInfo.getPassword());
        User user = User.builder()
                //设置账号，默认昵称为手机号
                .username(username)
                .nickName(otherAuthInfo.getPhone())
                .phone(otherAuthInfo.getPhone())
                .role("user")
                .password(password)
                .oauth(otherAuth.getId() + ":" + OthType.PHONE.getType())
                .avatar("@/assets/img/default.jpg")
                .build();
        return userMapper.insertUser(user) == 1;
    }
}
